import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import '../plugin_import/plugin_import.dart';

///
///  @author lizhi
///  @createTime 2020-05-11 10:50
///  @description :
///

class ScannerPage extends StatefulWidget {
  const ScannerPage({
    super.key,
  });

  static const routerName = 'ScannerPage';

  static Future<String?> push(BuildContext context) =>
      Navigator.of(context).push(MaterialPageRoute(
        settings: RouteSettings(name: routerName),
        builder: (context) => ScannerPage(),
      ));

  @override
  _ScannerPageState createState() => _ScannerPageState();
}

class _ScannerPageState extends State<ScannerPage>
    with TickerProviderStateMixin {
  NDScannerController? scannerController;
  double scannerHeight = 0;

  String? _scanResult;

  /// PDA扫描事件 id
  String? _pdaScanId;

  @override
  void initState() {
    _registerPDAScan(context);
    super.initState();
  }

  void _registerPDAScan(BuildContext context) {
    if (!kIsWeb) {
      _pdaScanId = PdaScanner.startPDAScan(
          context: context,
          onScanResult: (content) {
            // print('PDA 扫描结果    content：$content');
            _onScanResult(content, context);
          });
    }
  }

  @override
  void dispose() {
    controller?.dispose();
    if (!kIsWeb && _pdaScanId != null) {
      PdaScanner.stopPDAScan(_pdaScanId!);
    }
    super.dispose();
  }

  NDScannerController? controller;

  Future _onScanResult(String? result, BuildContext context) async {
    if (mounted) {
      _scanResult = result;
      setState(() {});
    }
    return Future.value();
  }

  @override
  Widget build(BuildContext context) {
    if (scannerHeight == 0) {
      scannerHeight = MediaQuery.of(context).size.height - 73;
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text('扫码示例页'),
        centerTitle: true,
      ),
      body: SafeArea(
        child: Column(
          children: [
            Center(
              child: Container(
                  padding: EdgeInsets.all(16),
                  child: Text('扫码识别结果：$_scanResult')),
            ),
            Expanded(
              child: NDScannerWidget(
                continueScan: true,
                onScannerCreate: (value) {
                  controller = value;
                },
                // height: scannerHeight,
                onResult: (result) async {
                  // print('result = $result');
                  await _onScanResult(result, context);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
